package mysql

import (
	"gorm.io/gorm"
	"inspector/internal/config"
	store "inspector/internal/dao"
	"inspector/pkg/db"
	"sync"
)

var (
	DB           *gorm.DB
	mysqlFactory store.Factory
	once         sync.Once
)

// InitDB New create a new gorm db instance with the given options.
func InitDB() (store.Factory, error) {
	mysqlConfig := config.Get().GetMySQLConfig()
	once.Do(func() {
		options := &db.Options{
			Host:                  mysqlConfig.Host,
			Username:              mysqlConfig.Username,
			Password:              mysqlConfig.Password,
			Database:              mysqlConfig.Database,
			MaxIdleConnections:    mysqlConfig.MaxIdleConnections,
			MaxOpenConnections:    mysqlConfig.MaxOpenConnections,
			MaxConnectionLifeTime: mysqlConfig.MaxConnectionLifeTime,
			LogLevel:              mysqlConfig.LogLevel,
			Logger:                db.NewLogger(mysqlConfig.LogLevel),
		}
		dbIns, err := db.New(options)
		if err != nil {
			panic(err)
		}
		// uncomment the following line if you need auto migration the given models
		// not suggested in production environment.
		//migrateDatabase(dbIns)
		mysqlFactory = &datastore{dbIns}
	})

	return mysqlFactory, nil
}

type datastore struct {
	db *gorm.DB
}

func (ds *datastore) User(tx *gorm.DB) store.UserStore {
	return newUser(tx)
}

func (ds *datastore) Event(tx *gorm.DB) store.EventStore {
	return newEvent(tx)
}

func (ds *datastore) Close() error {
	dc, err := ds.db.DB()
	if err != nil {
		return err
	}
	return dc.Close()
}

func (ds *datastore) DB() *gorm.DB {
	return ds.db
}

func migrateDatabase(db *gorm.DB) error {
	//if err := db.AutoMigrate(&entity.Donor{}); err != nil {
	//	return err
	//}
	return nil
}
